import { defineComponent, reactive, toRefs, computed } from "vue"
import { inject } from "vue"

import VeRadio from "amtf/components/radio"

import { EMIT_EVENTS } from "../util/constant"
import emitter from "amtf/utils/emitter"
import { useEmitter } from "amtf/hooks"

import { use样式 } from "amtf/hooks"
import { isNumber, isEmptyValue, getValByUnit, 拼组件名, isFunction, isBoolean, getRandomId } from "amtf/utils"
const 主名 = "table-body-radio-content"
const 组件名 = 拼组件名(主名)

export default defineComponent({
    name: 组件名,
    props: {
        radioOption: {
            type: Object,
            default: () => null,
        },
        rowKey: {
            type: [String, Number],
            required: true,
        },
        internalRadioSelectedRowKey: {
            type: [String, Number],
            default: null,
        },
    },
    setup(props) {
        const { dispatch } = useEmitter(inject("bodyid"))

        const state = reactive({
            isSelected: false,
        })

        const disabled = computed(() => {
            let result = false
            const { radioOption, rowKey } = props
            if (!radioOption) {
                return
            }
            const { disableSelectedRowKeys } = radioOption
            if (Array.isArray(disableSelectedRowKeys) && disableSelectedRowKeys.includes(rowKey)) {
                result = true
            }
            return result
        })

        const isControlledProp = computed(() => {
            const { radioOption } = props
            return radioOption && Object.keys(radioOption).includes("selectedRowKey")
        })

        watch(
            () => props.internalRadioSelectedRowKey,
            () => {
                state.isSelected = initSelected()
            },
            { immediate: true }
        )

        function initSelected() {
            state.isSelected = props.internalRadioSelectedRowKey === props.rowKey
        }

        function selectedChange() {
            const { isControlledProp } = state
            // 非受控
            if (!isControlledProp) {
                state.isSelected = true
            }
            dispatch(EMIT_EVENTS.RADIO_SELECTED_ROW_CHANGE, {
                rowKey: props.rowKey,
            })
        }

        return () => (
            <VeRadio
                class={拼样式名_提前传主名("radio-wrapper")}
                {...{
                    isControlled: true,
                    isSelected: state.isSelected,
                    disabled: disabled.value,
                    onRadioChange: () => selectedChange(),
                }}
            />
        )
    },
})
